from invidious import Channel as channel

from src.config import Config
from src.utils import *

class Channel(channel):

    def to_json(self):
        dct = {
            "type"          : "channel",
            "title"         : self.author,
            "authorId"      : self.authorId,
            "videos"        : self.latestVideos
        }

        return dct

    def is_subscribed(self, url: str=""):
        cfg = Config()
        subs_path = cfg.subs_path

        url = self.authorUrl[9:]
        subLine = -1

        with open(subs_path, 'r') as file:
            lines = file.readlines()
            for line in lines:
                subLine += 1
                if url in line: return True, subLine, lines

        return False, subLine, None

    def subscribe(self): 
        cfg = Config()
        subs_path = cfg.subs_path

        is_subscribed, _, _ = self.is_subscribed()
        if is_subscribed: return

        url = self.authorUrl[9:]

        with open(subs_path, 'r') as file:
            for line in file.readlines():
                if url in line: return file.close()
            file.close()

        with open(subs_path, 'a') as file:
            file.write(url+'\n')
            file.close()
    
    def unsubscribe(self):
        cfg = Config()
        subs_path = cfg.subs_path

        is_subscribed, _, _ = self.is_subscribed()
        if not is_subscribed: return

        url = self.authorUrl[9:]
        lines = []

        with open(subs_path, 'r') as file:
            lines = file.readlines()

        with open(subs_path, 'w') as file:
            for line in lines:
                if url not in line:
                    file.write(line)


